package pers.yurwisher.rubick.common.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.NestedRuntimeException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import pers.yurwisher.rubick.common.enums.tip.CustomTipEnum;
import pers.yurwisher.rubick.common.enums.tip.SystemCustomTipEnum;
import pers.yurwisher.rubick.common.exception.CustomException;
import pers.yurwisher.rubick.common.utils.PudgeUtil;
import pers.yurwisher.rubick.common.wrapper.R;

import javax.servlet.Servlet;
import java.util.List;
import java.util.Optional;

/**
 * controller  全局异常回调
 *
 * @author yq on 2020年9月17日 15:06:25
 */
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
// 使用 rubick.global.exception-handle.enabled 开启或关闭全局异常回调,默认开启
@ConditionalOnProperty(prefix = "rubick.global", name = "exception-handle", havingValue = "true", matchIfMissing = true)
@RestControllerAdvice
@Slf4j
public class GlobalDefaultExceptionHandler {

    public GlobalDefaultExceptionHandler() {
        log.info("auto config GlobalDefaultExceptionHandler");
    }


    /**
     * 全局异常
     */
    @ExceptionHandler(Throwable.class)
    public R<String> defaultErrorHandler(Throwable e) {
        log.error(e.getMessage(), e);
        return R.fail(CustomTipEnum.FAIL);
    }

    /**
     * 请求参数缺失
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public R<String> missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        return R.fail(e.getParameterName() + "缺失");
    }

    /**
     * 请求参数缺失
     */
    @ExceptionHandler(BindException.class)
    public R<String> bindExceptionExceptionHandler(BindException e) {
        return getExceptionDefaultMessage(e.getBindingResult(), e);
    }

    /**
     * 请求体缺失
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R<String> httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException e) {
        return R.fail("无有效请求体");
    }


    /**
     * 全局参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        return getExceptionDefaultMessage(e.getBindingResult(), e);
    }

    private R<String> getExceptionDefaultMessage(BindingResult bindingResult, Exception e) {
        List<ObjectError> errors = bindingResult.getAllErrors();
        if (CollectionUtil.isNotEmpty(errors)) {
            //返回第一个错误的信息
            Optional<ObjectError> optional = errors.stream().filter(error -> StrUtil.isNotEmpty(error.getDefaultMessage())).findFirst();
            return optional.map(objectError -> {
                if (objectError instanceof FieldError) {
                    FieldError fieldError = (FieldError) objectError;
                    String field = fieldError.getField();
                    //取出 field如 details[0].test 中的index
                    String rowNumber = ReUtil.getGroup1(PudgeUtil.SQUARE_BRACKETS_PATTERN, field);
                    String message = objectError.getDefaultMessage();
                    if (StrUtil.isNotEmpty(rowNumber)) {
                        message = StrBuilder.create("第[", Integer.toString(Integer.parseInt(rowNumber) + 1), "]条 ", message).toString();
                    }
                    return R.fail(message);
                } else {
                    return R.fail(objectError.getDefaultMessage());
                }
            }).orElseGet(() -> R.fail(CustomTipEnum.FAIL));
        } else {
            log.error("自定义校验错误: [{}]", e.getLocalizedMessage());
            return R.fail(CustomTipEnum.FAIL);
        }
    }

    /**
     * spring 抛出的异常
     */
    @ExceptionHandler(NestedRuntimeException.class)
    public R<String> nestedRuntimeExceptionHandler(NestedRuntimeException e) {
        log.info("spring 异常", e);
        return R.fail(CustomTipEnum.FAIL);
    }

    /**
     * 405
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<String> httpRequestMethodNotSupportedExceptionHandle(HttpRequestMethodNotSupportedException e) {
        return R.fail(CustomTipEnum.METHOD_NOT_ALLOWED);
    }

    /**
     * 415
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public R<String> httpMediaTypeNotSupportedExceptionHandle(HttpMediaTypeNotSupportedException e) {
        return R.fail(CustomTipEnum.UNSUPPORTED_MEDIA_TYPE);
    }

    /**
     * 404
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public R<String> noHandlerFoundExceptionHandle(NoHandlerFoundException e) {
        return R.fail(CustomTipEnum.NOT_FOUND);
    }


    /**
     * AuthenticationServiceException 认证错误
     */
    @ExceptionHandler(AuthenticationServiceException.class)
    public R<String> badCredentialsExceptionHandle(AuthenticationServiceException e) {
        Throwable throwable = e.getCause();
        if (throwable instanceof CustomException) {
            CustomException exception = (CustomException) throwable;
            return R.fail(exception.getTip());
        }
        return R.fail(SystemCustomTipEnum.AUTH_USERNAME_OR_PASSWORD_ERROR);
    }

    /**
     * BadCredentialsException 帐号或密码错误
     */
    @ExceptionHandler(BadCredentialsException.class)
    public R<String> badCredentialsExceptionHandle(BadCredentialsException e) {
        return R.fail(SystemCustomTipEnum.AUTH_USERNAME_OR_PASSWORD_ERROR);
    }

    /**
     * AccessDeniedException 无权操作
     */
    @ExceptionHandler(AccessDeniedException.class)
    public R<String> accessDeniedExceptionHandle(AccessDeniedException e) {
        return R.fail(SystemCustomTipEnum.PERMISSION_DENIED);
    }


    /**
     * 自定义异常回调
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException e) {
        return R.fail(e.getTip());
    }


}
